﻿using ArticleandSiteData;
using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace Dong
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class Uploadimage : Page
    {
        public ObservableCollection<BitmapImage> bmpobs = new ObservableCollection<BitmapImage>();
        public ObservableCollection<BitmapImage> updatebmpobs = new ObservableCollection<BitmapImage>();
        FileOpenPicker openPicker = new FileOpenPicker
        {
            SuggestedStartLocation = PickerLocationId.PicturesLibrary,
            ViewMode = PickerViewMode.Thumbnail
        };
        public Uploadimage()
        {
            this.InitializeComponent();
            openPicker.FileTypeFilter.Add(".bmp");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".jpg");
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            deviceid.Text = DeviceInfo.DeviceId;
            deviceidtb.Text= DeviceInfo.DeviceId;
            DataVMClass M = new DataVMClass();
            await M.Getcategorylist(listimg);
            await M.Getcategorylist(listcategory);
            imagelistview.ItemsSource = bmpobs;
            updateimagelistview.ItemsSource = updatebmpobs;
            Getexistseriesbydeviceid(DeviceInfo.DeviceId);
            base.OnNavigatedTo(e);
        }        
        StorageFile storeagfile;
        private async void choose_click(object sender, RoutedEventArgs e)
        {
            openPicker.FileTypeFilter.Clear();
            storeagfile = await openPicker.PickSingleFileAsync();
            if (storeagfile != null)
            {
                IRandomAccessStream irandom = await storeagfile.OpenAsync(FileAccessMode.Read);
                //对图像源使用流源
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(irandom);
                bmpobs.Add(bitmapImage);

            }
        }

        private async void upload_click(object sender, RoutedEventArgs e)
        {
            Mac mac = new Mac("UBubqd_IuffEWcUytSmz2bBTuXy9OdSW-kyPz8lQ", "-pH8neQ1GlMOHrd0Svs62f-JEHWrHID3eaUX0Q00");
            string bucket = "dongimage";
            string saveKey = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
            // 上传策略，参见 
            // https://developer.qiniu.com/kodo/manual/put-policy
            PutPolicy putPolicy = new PutPolicy();
            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;
            putPolicy.Scope = bucket;
            // 上传策略有效期(对应于生成的凭证的有效期)          
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 1;
            // 生成上传凭证，参见
            // https://developer.qiniu.com/kodo/manual/upload-token            
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);
            UploadManager um = new UploadManager();
            HttpResult result = await um.UploadFileAsync(storeagfile, saveKey, token);
            if (result.RefCode == 200)
            {
                string url = "https://api.bmob.cn/1/classes/imageinfo";
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("imageurl", "http://osavupwgi.bkt.clouddn.com/" + saveKey);
                dic.Add("imagetext", imagetext.Text);
                dic.Add("imagecategory", listimg.SelectedValue.ToString());
                bool r = await RequestHelper.addsimpleobject(url, dic);
                if (!r)
                {

                }
                else
                {
                    imagetext.Text = string.Empty;

                }
            }
            Console.WriteLine(result);
        }
        string deviceidstr = string.Empty;
        private async void Create_Series(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(seriesnamebox.Text)) return;
            string categoryurl = "https://api.bmob.cn/1/classes/seriesimage";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("name_sereis", seriesnamebox.Text);
            dic.Add("deviceid", deviceid.Text);
            if (listcategory.SelectedValue != null)
            {
                dic.Add("category", listcategory.SelectedValue.ToString());
            }
            var isok = await RequestHelper.addsimpleobject(categoryurl, dic);
            if (isok)
            {
                seriesnamebox.Text = string.Empty;
            }
            else
            {

            }
        }
        private async void Getexistseriesbydeviceid(string str)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();           
            string querystr = "https://api.bmob.cn/1/classes/seriesimage?where={\"deviceid\":" + "\"" + str + "\"}";
            string result = await RequestHelper.GetHttpstringrequest(querystr);
            seriesimageobject m = JsonConvert.DeserializeObject<seriesimageobject>(result);
            listseries.ItemsSource = m.results;
        }
        private async void choose_multipic(object sender, RoutedEventArgs e)
        {

            // Filter to include a sample subset of file types.
            openPicker.FileTypeFilter.Clear();
            openPicker.FileTypeFilter.Add(".bmp");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".jpg");
            var storeagfilelist = await openPicker.PickMultipleFilesAsync();
            if (storeagfilelist != null)
            {
                foreach (var a in storeagfilelist)
                {
                     var b= await uploadtoqiniu(a,seriesnamebox.Text);
                    if (b)
                    {
                        IRandomAccessStream irandom = await a.OpenAsync(FileAccessMode.Read);
                        //对图像源使用流源
                        BitmapImage bitmapImage = new BitmapImage();
                        await bitmapImage.SetSourceAsync(irandom);
                        bmpobs.Add(bitmapImage);
                    }
                }

            }
        }

        private async void updatechoose_multipic(object sender, RoutedEventArgs e)
        {
            var storeagfilelist = await openPicker.PickMultipleFilesAsync();
            if (storeagfilelist != null)
            {
                foreach (var a in storeagfilelist)
                {
                    if (listseries.SelectedValue != null)
                    {
                        var b = await addseriesimage(a, listseries.SelectedValue.ToString());
                        if (b)
                        {
                            IRandomAccessStream irandom = await a.OpenAsync(FileAccessMode.Read);
                            BitmapImage bitmapImage = new BitmapImage();
                            await bitmapImage.SetSourceAsync(irandom);
                            updatebmpobs.Add(bitmapImage);
                        }
                    }
                }

            }
        }
        private async Task<bool> uploadtoqiniu(StorageFile file,string seriesname)
        {
            Mac mac = new Mac("UBubqd_IuffEWcUytSmz2bBTuXy9OdSW-kyPz8lQ", "-pH8neQ1GlMOHrd0Svs62f-JEHWrHID3eaUX0Q00");
            string bucket = "dongimage";
            string saveKey = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
            // 上传策略，参见 
            // https://developer.qiniu.com/kodo/manual/put-policy
            PutPolicy putPolicy = new PutPolicy();
            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;
            putPolicy.Scope = bucket;
            // 上传策略有效期(对应于生成的凭证的有效期)          
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 1;
            // 生成上传凭证，参见
            // https://developer.qiniu.com/kodo/manual/upload-token            
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);
            UploadManager um = new UploadManager();
            HttpResult result = await um.UploadFileAsync(file, saveKey, token);
            if (result.RefCode == 200)
            {
                string url = "https://api.bmob.cn/1/classes/imageinfo";
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("imageurl", "http://osavupwgi.bkt.clouddn.com/" + saveKey);
             
                // dic.Add("imagetext", imagetext.Text);
                if (listcategory.SelectedValue != null)
                {
                    dic.Add("imagecategory", listcategory.SelectedValue.ToString());
                }
                bool r = await RequestHelper.addsimpleobject(url, dic);
                return r;
            }
            return false;
        }
        private async Task<bool> addseriesimage(StorageFile file, string seriesname)
        {
            Mac mac = new Mac("UBubqd_IuffEWcUytSmz2bBTuXy9OdSW-kyPz8lQ", "-pH8neQ1GlMOHrd0Svs62f-JEHWrHID3eaUX0Q00");
            string bucket = "dongimage";
            string saveKey = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
            // 上传策略，参见 
            // https://developer.qiniu.com/kodo/manual/put-policy
            PutPolicy putPolicy = new PutPolicy();
            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;
            putPolicy.Scope = bucket;
            // 上传策略有效期(对应于生成的凭证的有效期)          
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 1;
            // 生成上传凭证，参见
            // https://developer.qiniu.com/kodo/manual/upload-token            
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(mac, jstr);
            UploadManager um = new UploadManager();
            HttpResult result = await um.UploadFileAsync(file, saveKey, token);
            if (result.RefCode == 200)
            {
                string url = "https://api.bmob.cn/1/classes/seriesimagedetail";
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("imageurl", "http://osavupwgi.bkt.clouddn.com/" + saveKey);
                dic.Add("seriesname", seriesname);
                // dic.Add("imagetext", imagetext.Text);
               
                bool r = await RequestHelper.addsimpleobject(url, dic);
                return r;
            }
            return false;
        }

        private async void listseries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            updatebmpobs.Clear();
            string selectedvalue = listseries.SelectedValue.ToString();
            string querystr = "https://api.bmob.cn/1/classes/seriesimagedetail?where={\"seriesname\":" + "\"" + selectedvalue + "\"}";
            string result = await RequestHelper.GetHttpstringrequest(querystr);
            seriesimagedetailobject seriesnameobj = JsonConvert.DeserializeObject<seriesimagedetailobject>(result);
            foreach(var a in seriesnameobj.results)
            {
                BitmapImage btm = new BitmapImage(new Uri(a.imageurl, UriKind.RelativeOrAbsolute));
                updatebmpobs.Add(btm);
            }
        }
    }
}
